<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="state.goodForm" :rules="state.rules" ref="goodRef" :disabled="type == 'detail'"
        label-width="105px" class="goodForm">
        <el-form-item required label="商品分类">
          <el-cascader :placeholder="state.defaultCate" style="width: 300px" :props="state.category"
            @change="handleChangeCate"></el-cascader>
        </el-form-item>
        <el-form-item required label="品牌" prop="goodsBrandId">
          <el-select v-model="state.goodForm.goodsBrandId" placeholder="请选择品牌" style="width: 300px">
            <el-option v-for="item in state.brands" :key="item.brandId" :label="item.brandName" :value="item.brandId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input style="width: 300px" v-model="state.goodForm.goodsName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item required label="轮播图" prop="goodsCarouselList">
          <el-upload v-model:file-list="state.goodForm.goodsCarouselList" :action="state.uploadImgServer" multiple
            accept="jpg,jpeg,png" :headers="{ token: state.token }" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleCarouselSuccess">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input style="width: 300px" type="textarea" v-model="state.goodForm.goodsIntro"
            placeholder="请输入商品简介(100字)"></el-input>
        </el-form-item>
        <div class="add-goods flex-a">
          <div><span>*</span>新增商品规格</div>
          <el-button type="primary" round @click="addGoods">添加</el-button>
        </div>
        <div class="goods-list">
          <el-table :load="state.loading" :data="state.tableData" tooltip-effect="dark" style="width: 100%">
            <el-table-column prop="specName" label="商品规格">
              <template #default="scope">
                <el-input placeholder="请输入商品规格" v-model="scope.row.specName" clearable></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="specOriginalPrice" label="商品价格">
              <template #default="scope">
                <el-input placeholder="请输入商品价格" @input="inputPrice(scope.row, scope.$index)"
                  v-model="scope.row.specOriginalPrice" clearable>
                  <template #prepend>
                    <el-button>￥</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="specSellingPrice" label="商品售卖价">
              <template #default="scope">
                <el-input placeholder="请输入商品售卖价" @input="inputOrgPrice(scope.row, scope.$index)"
                  v-model="scope.row.specSellingPrice" clearable>
                  <template #prepend>
                    <el-button>￥</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="distPrice" label="商品佣金">
              <template #default="scope">
                <el-input placeholder="请输入商品佣金" v-model="scope.row.distPrice" clearable>
                  <template #prepend>
                    <el-button>￥</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="stockNum" label="商品库存">
              <template #default="scope">
                <el-input placeholder="请输入商品库存" v-model="scope.row.stockNum" clearable></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="tag" label="商品标签">
              <template #default="scope">
                <el-input placeholder="请输入商品标签" v-model="scope.row.tag" clearable></el-input>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="上架状态">
              <template #default="scope">
                <el-switch v-model="scope.row.status" size="large" active-text="上架" inactive-text="下架" active-value="0"
                  inactive-value="1" />
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="140" v-if="state.type != 'detail'">
              <template #default="scope">
                <a style="cursor: pointer; margin-right: 10px" @click="handleDel(scope.row, scope.$index)">删除</a>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item label="显示价格" prop="originalPrice">
          <el-input type="text" style="width: 300px" v-model="state.goodForm.originalPrice"
            placeholder="请输入显示价格"></el-input>
        </el-form-item>
        <el-form-item label="显示售价" prop="sellingPrice">
          <el-input type="text" style="width: 300px" v-model="state.goodForm.sellingPrice"
            placeholder="请输入显示售价"></el-input>
        </el-form-item>
        <el-form-item label="限购数量" prop="quota">
          <el-input type="text" style="width: 300px" v-model="state.goodForm.quota"
            placeholder="0为不限购，其他数字为限购数量"></el-input>
        </el-form-item>
        <el-form-item label="商品佣金" prop="distPrice">
          <el-input type="text" style="width: 300px" v-model="state.goodForm.distPrice" placeholder="请输入佣金"></el-input>
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-input style="width: 300px" v-model="state.goodForm.tag" placeholder="请输入商品小标签"></el-input>
        </el-form-item>
        <div class="cx-list">
          <div class="cx-item" v-for="(item, index) in state.goodForm.cxList">
            <el-form-item label="促销名称" prop="tag">
              <el-input style="width: 300px" v-model="state.goodForm.cxList[index].cxName"
                placeholder="请输入促销名称"></el-input>
              <el-icon size="26" v-if="index == 0">
                <CirclePlusFilled color="#67C23A" @click="addCx" />
              </el-icon>
              <el-icon size="26">
                <RemoveFilled color="#F56C6C" @click="reduceCx(index)" />
              </el-icon>
            </el-form-item>
            <el-form-item label="促销简介" prop="tag">
              <el-input style="width: 300px" v-model="state.goodForm.cxList[index].cxInfo"
                placeholder="请输入促销简介"></el-input>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="上架状态" prop="goodsSellStatus">
          <el-radio-group v-model="state.goodForm.goodsSellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item required label="商品主图" prop="goodsCoverImg">
          <el-upload class="avatar-uploader" :action="state.uploadImgServer" accept="jpg,jpeg,png" :headers="{
            token: state.token
          }" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUrlSuccess">
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.goodForm.goodsCoverImg"
              :src="state.goodForm.goodsCoverImg" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item v-if="state.type != 'detail'">
          <el-button type="primary" @click="submitAdd()">{{ state.id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" style="width: 100%;" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer } from '@/utils'
const { proxy } = getCurrentInstance()
const editor = ref(null)
const goodRef = ref(null)
const route = useRoute()
const router = useRouter()
const { id } = route.query
const { type } = route.query
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const state = reactive({
  loading: false,
  tableData: [{}],
  uploadImgServer,
  token: localGet('token') || '',
  id: id,
  type: type,
  defaultCate: '',
  goodForm: {
    goodsName: '',
    goodsCarouselList: [],
    goodsIntro: '',
    originalPrice: '',
    sellingPrice: '',
    stockNum: '',
    goodsSellStatus: '0',
    goodsCoverImg: '',
    tag: '',
    spec: '',
    distPrice: '',
    quota: '',
    cxList: [
      { cxName: "", cxInfo: '' }
    ]
  },
  rules: {
    goodsName: [
      { required: 'true', message: '请填写商品名称', trigger: ['change'] }
    ],
    originalPrice: [
      { required: 'true', message: '请填写显示价格', trigger: ['change'] }
    ],
    sellingPrice: [
      { required: 'true', message: '请填写显示售价', trigger: ['change'] }
    ],
    stockNum: [
      { required: 'true', message: '请填写商品库存', trigger: ['change'] }
    ],
    distPrice: [
      { required: 'true', message: '请填写商品佣金', trigger: ['change'] }
    ]
  },
  brands: [],
  categoryId: '',
  category: {
    lazy: true,
    lazyLoad(node, resolve) {
      const { level = 0, value } = node
      axios.get('/categories', {
        params: {
          pageNumber: 1,
          pageSize: 1000,
          categoryLevel: level + 1,
          parentId: value || 0
        }
      }).then(res => {
        const list = res.list
        const nodes = list.map(item => ({
          value: item.categoryId,
          label: item.categoryName,
          leaf: level > 1
        }))
        resolve(nodes)
      })
    }
  }
})
let instance
onMounted(() => {
  instance = new WangEditor(editor.value)
  instance.config.showLinkImg = false
  instance.config.showLinkImgAlt = false
  instance.config.showLinkImgHref = false
  instance.config.uploadImgMaxSize = 30 * 1024 * 1024
  instance.config.uploadFileName = 'file'
  instance.config.uploadImgHeaders = {
    token: state.token
  }
  // 图片返回格式不同，需要自定义返回格式
  instance.config.uploadImgHooks = {
    // 图片上传并返回了结果，想要自己把图片插入到编辑器中
    // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
    customInsert: function (insertImgFn, result) {
      console.log('result', result)
      // result 即服务端返回的接口
      // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
      if (result.code == 200 && result.url) {
        // result.message.forEach(item => insertImgFn(item))
        insertImgFn(result.url)
      }
    }
  }
  instance.config.uploadImgServer = uploadImgsServer
  Object.assign(instance.config, {
    onchange() {
      console.log('change')
    },
  })
  instance.create()
  if (state.type == 'detail') {
    instance.disable()
  } else {
    instance.enable()
  }
  if (id) {
    axios.get(`/goods/${id}`).then(res => {
      const { goods, firstCategory, secondCategory, thirdCategory } = res
      state.goodForm = {
        goodsName: goods.goodsName,
        goodsIntro: goods.goodsIntro,
        goodsCarouselList: goods.goodsCarouselList,
        originalPrice: goods.originalPrice,
        sellingPrice: goods.sellingPrice,
        stockNum: goods.stockNum,
        goodsSellStatus: String(goods.goodsSellStatus),
        goodsCoverImg: proxy.$filters.prefix(goods.goodsCoverImg),
        tag: goods.tag,
        spec: goods.spec,
        goodsBrandId: goods.goodsBrandId,
        distPrice: goods.distPrice,
        quota: goods.quota,
        cxList: goods.cxList
      }
      state.tableData = goods.specInfoList
      state.categoryId = goods.goodsCategoryId
      state.defaultCate = `${firstCategory.categoryName}/${secondCategory.categoryName}/${thirdCategory.categoryName}`
      if (instance) {
        // 初始化商品详情 html
        instance.txt.html(goods.goodsDetailContent)
      }
    })
  }
  axios.get(`/getBrandList`).then(res => {
    state.brands = res
  })
})
onBeforeUnmount(() => {
  instance.destroy()
  instance = null
})
const reduceCx = (index) => {
  if (state.goodForm.cxList.length > 1) {
    state.goodForm.cxList.splice(index, 1)
  } else {
    ElMessage({
      message: '至少保留一条。',
      type: 'warning',
    })
  }
}
const addCx = () => {
  state.goodForm.cxList.push({ cxName: '', cxInfo: '' })
}
const inputPrice = (row, index) => {
  if (index == 0) {
    state.goodForm.originalPrice = row.specOriginalPrice
  }
}
const inputOrgPrice = (row, index) => {
  if (index == 0) {
    state.goodForm.sellingPrice = row.specSellingPrice
  }
}
const submitAdd = () => {
  goodRef.value.validate((vaild) => {
    if (vaild) {
      // 默认新增用 post 方法
      let httpOption = axios.post
      let list = state.goodForm.goodsCarouselList
      let goodsCarouselList = ''
      if (!id) {
        list.forEach(item => {
          goodsCarouselList += item.response.url + ','
        })
      } else {
        list.forEach(item => {
          goodsCarouselList += item.response ? item.response.url + ',' : item.url + ','
        })
      }
      let params = {
        goodsCategoryId: state.categoryId,
        goodsCarouselList: goodsCarouselList,
        goodsCoverImg: state.goodForm.goodsCoverImg,
        goodsDetailContent: instance.txt.html(),
        goodsIntro: state.goodForm.goodsIntro,
        goodsName: state.goodForm.goodsName,
        goodsSellStatus: state.goodForm.goodsSellStatus,
        tag: state.goodForm.tag,
        specInfoList: state.tableData,
        goodsBrandId: state.goodForm.goodsBrandId,
        distPrice: state.goodForm.distPrice,
        originalPrice: state.goodForm.originalPrice,
        sellingPrice: state.goodForm.sellingPrice,
        quota: state.goodForm.quota,
        cxList: state.goodForm.cxList
      }
      if (id) {
        params.goodsId = id
        // 修改商品使用 put 方法
        httpOption = axios.put
      }
      httpOption('/goods', params).then(() => {
        ElMessage.success(id ? '修改成功' : '添加成功')
        router.push({ path: '/good' })
      })
    }
  })
}
const addGoods = () => {
  state.tableData.push({})
}
const handleDel = (row, index) => {
  console.log(row, index)
  state.tableData.splice(index, 1)
}
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const handleUrlSuccess = (val) => {
  state.goodForm.goodsCoverImg = val.url || ''
}
const handleCarouselSuccess = (val) => {

}
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
const handleChangeCate = (val) => {
  state.categoryId = val[2] || 0
}
</script>

<style scoped>
.add {
  display: flex;
}

.add-container {
  flex: 1;
  height: 100%;
}

.add-goods div {
  margin-right: 10px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.add-goods div span {
  color: #F66C6C;
}

.goods-list {
  margin-bottom: 10px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}

.cx-list .el-icon {
  margin: 0 10px;
}

.cx-list .el-icon:hover {
  cursor: pointer;
}
</style>